package elasticsearch

import (
	"bawei_2112a_shop/model/mysql"
	"context"
	"encoding/json"
	"fmt"
	"github.com/elastic/go-elasticsearch/esapi"
	"log"
	"strconv"
	"strings"
)

func AddGoodsToEs(index string, goods *mysql.Goods) {

	str, err := json.Marshal(goods)
	if err != nil {
		log.Fatalf("同步商品信息到 ES 失败：%s", err)
		return
	}

	req := esapi.IndexRequest{
		Index:      index,
		DocumentID: strconv.Itoa(int(goods.ID)),
		Body:       strings.NewReader(string(str)),
		Refresh:    "true",
	}

	// Perform the request with the client.
	res, err := req.Do(context.Background(), EsClient)
	if err != nil {
		log.Fatalf("同步商品信息到 ES 失败: %s", err)
	}
	defer res.Body.Close()
}

func GetGoodsFromEs(field, keyword, index string) {
	str := map[string]interface{}{}
	if keyword == "" {
		str = map[string]interface{}{
			"query": map[string]interface{}{
				"match_all": map[string]interface{}{},
			},
		}
	} else {
		str = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					field: keyword,
				},
			},
			"highlight": map[string]interface{}{
				"fields": map[string]interface{}{
					field: map[string]interface{}{},
				},
			},
		}
	}

	body, _ := json.Marshal(str)

	res, err := EsClient.Search(
		EsClient.Search.WithContext(context.Background()),
		EsClient.Search.WithIndex(index),
		EsClient.Search.WithBody(strings.NewReader(string(body))),
		EsClient.Search.WithTrackTotalHits(true),
		EsClient.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("ERROR: %s", err)
	}
	defer res.Body.Close()

	var r map[string]interface{}

	if err = json.NewDecoder(res.Body).Decode(&r); err != nil {
		log.Fatalf("Error parsing the response body: %s", err)
	}

	//正常情况该结构体在 srv 的 proto 生成包内
	type g struct {
		GoodsTitle string
		GoodsPrice float64
		GoodsStock int64
		GoodsCover string
	}

	var retData []*g

	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		//fmt.Println(hit.(map[string]interface{})["_source"])
		source := hit.(map[string]interface{})["_source"]
		retData = append(retData, &g{
			GoodsTitle: source.(map[string]interface{})["GoodsTitle"].(string),
			GoodsPrice: source.(map[string]interface{})["GoodsPrice"].(float64),
			GoodsStock: int64(source.(map[string]interface{})["GoodsStock"].(float64)),
			GoodsCover: source.(map[string]interface{})["GoodsCover"].(string),
		})
	}

	// 定义返回值类型，直接返回切片就行
	fmt.Println(retData)
}
